package com.hhkj.admin.common.util;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Component
public class WechatAppUtil {

    public static String appId;

    public static String appKey;

    public static String page;

    public static String environment;

    public static String postToken() throws Exception {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appKey;
        URL url = new URL(requestUrl);         // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in;
        if (requestUrl.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder result = new StringBuilder();
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result.append(getLine);
        }
        JSONObject jsonObject = JSONObject.parseObject(java.lang.String.valueOf(result));
        return jsonObject.getString("access_token");
    }

    public static InputStream generateQrCode(String scene) throws Exception {
            String accessToken = postToken();
            //调用微信接口生成二维码
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 获取URLConnection对象对应的输出流
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            //这就是你二维码里携带的参数 String型  名称不可变
            paramJson.put("scene", scene);
            //注意该接口传入的是page而不是path
            paramJson.put("page", page);
            //这是设置扫描二维码后跳转的页面
            paramJson.put("width", 200);
            paramJson.put("env_version", environment);
            paramJson.put("check_path", false);
//            paramJson.put("is_hyaline", true);
//            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();

            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            return decorate(bis, scene);
    }

    public static InputStream decorate(InputStream inputStream, String num) throws IOException {
        BufferedImage image = ImageIO.read(inputStream);

        // Create a new BufferedImage with increased height
        int newHeight = image.getHeight() + 40; // Adjust the height as needed
        BufferedImage newImage = new BufferedImage(image.getWidth(), newHeight, BufferedImage.TYPE_INT_RGB);

        // Create a graphics context on the new image
        Graphics2D g = newImage.createGraphics();

        // Set rendering hints for better text quality
        Map<RenderingHints.Key, Object> renderingHints = new HashMap<>();
        renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        renderingHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHints(renderingHints);

        // Set the background color
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, newImage.getWidth(), newImage.getHeight());

        // Draw the original image onto the new image
        g.drawImage(image, 0, 40, null);

        // Set the font and color for the text
        Font font = new Font("SimSun", Font.BOLD, 20);
        g.setFont(font);
        g.setColor(Color.BLACK);

        // Add your text at specific coordinates (x, y)
        String text = "NO:" + num;
        FontMetrics metrics = g.getFontMetrics(font);
        int textWidth = metrics.stringWidth(text);
        int x = (image.getWidth() - textWidth) / 2; // Adjust the x-coordinate as needed
        g.drawString(text, x, 30);

        // Dispose the graphics context
        g.dispose();

        // Save the modified image
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(newImage, "jpg", outputStream);

        // Convert byte array to input stream
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
        return byteArrayInputStream;
    }

    @Value("${wx.appid}")
    public void setAppId(String appId) {
        WechatAppUtil.appId = appId;
    }

    @Value("${wx.secret}")
    public void setAppKey(String appKey) {
        WechatAppUtil.appKey = appKey;
    }

    @Value("${wx.page}")
    public void setPage(String page) {
        WechatAppUtil.page = page;
    }

    @Value("${wx.environment}")
    public void setEnvironment(String environment) {
        WechatAppUtil.environment = environment;
    }
}
